package com.group.service.impl;

import com.group.mapper.LoginMapper;
import com.group.service.LoginService;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.entity.Record;
import pojo.entity.User;
import pojo.vo.BaseRespVO;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Properties;

@Service
public class LoginServiceImpl implements LoginService {

    String stringBuilder ="";

    @Autowired
    LoginMapper loginMapper;

    @Override
    public User checkUser(String userName, String password) {
        if (!"".equals(userName)){
            User userByName = loginMapper.findUserByName(userName);     //获得当前用户信息
            if (userByName!=null){
                String password1 = userByName.getPassword();
                System.out.println(userByName);
                if (password.equals(password1)){
                    return userByName;
                }
            }
        }
        return null;
    }

    @Override
    public String sendEmail(String email, HttpServletResponse response) {
        Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密，否则会失败
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            // 创建session
            Session session = Session.getInstance(prop);
            // 通过session得到transport对象
            Transport ts = session.getTransport();
            // 连接邮件服务器：邮箱类型，帐号，POP3/SMTP协议授权码 163使用：smtp.163.com
            ts.connect("smtp.qq.com", "642523090", "inhjaypntpetbeeg");
            // 创建邮件
            Message message = createSimpleMail(session,response,email);
            // 发送邮件
//        for (int i = 0; i < 10; i++) {
            ts.sendMessage(message, message.getAllRecipients());
//        }
            ts.close();
        } catch (MessagingException | GeneralSecurityException | IOException e) {
            e.printStackTrace();
        }
        return stringBuilder;
    }

    @Override
    public void saveUser(User user) {
        loginMapper.saveUser(user);
    }

    @Override
    public void saveLog(Record record) {
        loginMapper.saveLog(record);
    }

    /**
     * 商品查询修改操作
     * @param userId
     * @param sum
     * @return
     */
    @Override
    public Record logAction(Long userId, Integer sum) {
        List<Record> log = loginMapper.findLog(userId);
        Record record=log.get(log.size()-1);

        Record record1=new Record(record.getRecordId(),record.getSumOrder()+1,record.getSumGood()+sum);
        loginMapper.updateLog(record1);
        return record;
    }

    @Override
    public void updateLog(Record record) {
        loginMapper.updateLog(record);
    }


    /**
     * @Method: createSimpleMail
     * @Description: 创建一封只包含文本的邮件
     */
    public MimeMessage createSimpleMail(Session session, HttpServletResponse resp, String userEmail) throws MessagingException, IOException {
        //  获取6为随机验证码
        stringBuilder ="";
        String[] letters = new String[] {
                "q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
                "Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
                "0","1","2","3","4","5","6","7","8","9"};
        for (int i = 0; i < 6; i++) {
            stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)];
        }

        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("642523090@qq.com"));
        // 指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(userEmail));
        // 邮件的标题
        message.setSubject("《达摩院》");
        // 邮件的文本内容
        message.setContent("欢迎您注册【晓博商城】,账号注册验证码为(三分钟有效):"+stringBuilder+",请勿回复此邮箱", "text/html;charset=UTF-8");
        /*message.setContent("上课摸鱼！！！！！！！！", "text/html;charset=UTF-8");*/
        //创建标准返回对象
        BaseRespVO baseRespVO=new BaseRespVO();
        //获取成功对象
        BaseRespVO success = baseRespVO.success(stringBuilder);
        // 返回创建好的邮件对象
        return message;
    }

}
